﻿using System;

namespace Bricks
{

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TKernel"></typeparam>
    public abstract class DisposableFacadeBase<TKernel> : FacadeBase<TKernel>
    {

        /// <summary>
        /// 
        /// </summary>
        private bool _disposing = false;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="kernel"></param>
        protected DisposableFacadeBase(TKernel kernel) :
            base(() => kernel)
        {
            if (kernel == null)
            {
                throw new ArgumentNullException("kernel");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposing)
            {
                if (disposing)
                {
                    _disposing = true;

                    IDisposable disposable = Kernel as IDisposable;

                    if (disposable != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        ~DisposableFacadeBase()
        {
            Dispose(false);
        }
    }
}
